package com.cgwx.service.impl;

import com.cgwx.auth.util.TreeUtil.TreeUtils;
import com.cgwx.config.BusinessException;
import com.cgwx.entity.*;
import com.cgwx.mapper.*;
import com.cgwx.service.IAuthorityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class AuthorityServiceImpl implements IAuthorityService {
    @Resource
    private AuthorityMapper authorityMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private FolderMapper folderMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private DeptMapper deptMapper;

    @Value("${USService}")
    private String USService;

    @Value("${fileManagerAccount}")
    private String fileManagerAccount;
    @Resource
    private PersonalRecycleBinMapper personalRecycleBinMapper;

    @Override
    public List<Authority> getAuthority(String account, String entityId) {
        Authority authority = new Authority();
        authority.setEntityId(entityId);
        return authorityMapper.getAuthority(authority);
    }

    public List<Authority> getAuthority(Authority authority) {
        return authorityMapper.getAuthority(authority);
    }

    @Override
    public boolean insertAuthority(Authority authority) {
        return authorityMapper.insertAuthority(authority);
    }

    public List<UsUser> getDeptMember(String deptId) {
        RestTemplate restTemplate = new RestTemplate();
        String url = USService + "/queryUsersByDeptId?deptId=" + deptId;
        ResponseEntity<List<UsUser>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<UsUser>>() {}
        );
        return response.getBody();
    }

    @Override
    public List<AuthorityInfo> getMemberAuthority(String account, String deptId, String entityId) {
        Authority authorityCompany = new Authority();
        authorityCompany.setEntityId(entityId);
        authorityCompany.setPermissionType("company");
        List<Authority> authoritiesCompany = authorityMapper.getNewAuthority(authorityCompany);
        //单人管理员单独显示
        Authority authorityStaffManager = new Authority();
        authorityStaffManager.setEntityId(entityId);
        authorityStaffManager.setPermissionType("staff");
        authorityStaffManager.setAuthorityLevel("4");
        List<Authority> authoritiesStaffManagers = authorityMapper.getAuthority(authorityStaffManager);//所有单人管理员
        Map<String, String> authoritiesStaffManagersMap = new HashMap<>();
        for(Authority authority: authoritiesStaffManagers) authoritiesStaffManagersMap.put(authority.getPermissionId(), authority.getPermissionName());
        List<AuthorityInfo> authorityInfos = new ArrayList<>();
        if(authoritiesCompany.isEmpty() || authoritiesCompany.get(0).getAuthorityLevel().equals("0") || authoritiesCompany.get(0).getAuthorityLevel().equals("0.5")){
            //无公司全部人员的权限
            Authority authorityDept0 = new Authority();
            authorityDept0.setPermissionType("dept");
            authorityDept0.setEntityId(entityId);
            List<Authority> authoritiesDept = authorityMapper.getNewAuthority(authorityDept0);
            if(authoritiesDept.isEmpty() || authoritiesDept.get(0).getAuthorityLevel().equals("0") || authoritiesDept.get(0).getAuthorityLevel().equals("0.5")){
                //无部门权限
                Authority authorityStaff0 = new Authority();
                authorityStaff0.setPermissionType("staff");
                authorityStaff0.setEntityId(entityId);
                List<Authority> authoritiesStaff = authorityMapper.getNewAuthority(authorityStaff0);
                //单人管理员
                for(String key: authoritiesStaffManagersMap.keySet()){
                    AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                    authorityInfoStaff.setPermissionId(key);
                    if(key.equals(fileManagerAccount)) authorityInfoStaff.setPermissionName("系统文件管理员");
                    else authorityInfoStaff.setPermissionName(authoritiesStaffManagersMap.get(key));
                    authorityInfoStaff.setAuthorityLevel("4");
                    authorityInfos.add(0, authorityInfoStaff);
                }
                //都是人，不是管理员
                for(Authority authorityStaff: authoritiesStaff){
                    if(!authoritiesStaffManagersMap.containsKey(authorityStaff.getPermissionId())){
                        AuthorityInfo authorityInfo = new AuthorityInfo();
                        authorityInfo.setPermissionId(authorityStaff.getPermissionId());
                        authorityInfo.setPermissionName(authorityStaff.getPermissionName());
                        authorityInfo.setAuthorityLevel(authorityStaff.getAuthorityLevel());
                        authorityInfos.add(authorityInfo);
                    }
                }
            }
            else{
                //有部门权限
                Authority authorityStaff0 = new Authority();
                authorityStaff0.setPermissionType("staff");
                authorityStaff0.setEntityId(entityId);
                List<Authority> authoritiesStaff = authorityMapper.getNewAuthority(authorityStaff0);//所有单人权限
                Set<String> hasStaff = new HashSet<>();
                Map<String, Timestamp> authoritiesStaffIdTime = new HashMap<>();
                Map<String, String> authoritiesStaffIdLevel = new HashMap<>();
                for(Authority authorityStaff: authoritiesStaff){
                    //存储单人的更新时间和权限
                    authoritiesStaffIdTime.put(authorityStaff.getPermissionId(), authorityStaff.getUpdateTime());
                    authoritiesStaffIdLevel.put(authorityStaff.getPermissionId(), authorityStaff.getAuthorityLevel());
                }
                for(Authority authorityDept: authoritiesDept){
                    UsUser user = new UsUser();
                    user.setDeptId(authorityDept.getPermissionId());
                    List<UsUser> users = userMapper.getUser(user);//部门所有人
                    AuthorityInfo authorityInfoDept = new AuthorityInfo();
                    authorityInfoDept.setPermissionId(authorityDept.getPermissionId());
                    authorityInfoDept.setPermissionName(authorityDept.getPermissionName());
                    for(UsUser user1: users){
                        AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                        authorityInfoStaff.setPermissionId(user1.getAccount());
                        if(user1.getAccount().equals(fileManagerAccount)) authorityInfoStaff.setPermissionName("系统文件管理员");
                        else authorityInfoStaff.setPermissionName(user1.getName() + "_" + user1.getAccount());
                        authorityInfoStaff.setAuthorityLevel(authorityDept.getAuthorityLevel());
                        Timestamp updateTime = authoritiesStaffIdTime.get(user1.getAccount());
                        if(updateTime != null){//有单人
                            if(authoritiesStaffManagersMap.containsKey(user1.getAccount())) authorityInfoStaff.setAuthorityLevel("4");
                            else if(updateTime.compareTo(authorityDept.getUpdateTime()) >= 0){//单人的最新
                                authorityInfoStaff.setAuthorityLevel(authoritiesStaffIdLevel.get(user1.getAccount()));
                            }
                            hasStaff.add(user1.getAccount());
                        }
                        if(authorityInfoStaff.getAuthorityLevel().equals("4")) authorityInfoDept.addFirstChildren(authorityInfoStaff);
                        else authorityInfoDept.addChildren(authorityInfoStaff);
                    }
                    if(authorityDept.getAuthorityLevel().equals("4")) authorityInfos.add(0, authorityInfoDept);
                    else authorityInfos.add(authorityInfoDept);
                }
                //单人管理员
                for(String key: authoritiesStaffManagersMap.keySet()){
                    AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                    authorityInfoStaff.setPermissionId(key);
                    if(key.equals(fileManagerAccount)) authorityInfoStaff.setPermissionName("系统文件管理员");
                    else authorityInfoStaff.setPermissionName(authoritiesStaffManagersMap.get(key));
                    authorityInfoStaff.setAuthorityLevel("4");
                    authorityInfos.add(0, authorityInfoStaff);
                }
                //剩下的其他单人
                for(Authority authorityStaff: authoritiesStaff){
                    if(!hasStaff.contains(authorityStaff.getPermissionId()) && !authoritiesStaffManagersMap.containsKey(authorityStaff.getPermissionId())){//部门中不存在的单人
                        AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                        authorityInfoStaff.setPermissionId(authorityStaff.getPermissionId());
                        authorityInfoStaff.setPermissionName(authorityStaff.getPermissionName() + "_" + authorityStaff.getPermissionId());
                        authorityInfoStaff.setAuthorityLevel(authorityStaff.getAuthorityLevel());
                        authorityInfos.add(authorityInfoStaff);
                    }
                }
            }
        }
        else{
            authorityCompany = authoritiesCompany.get(0);
            //有公司全部人员的权限
            List<UsDept> depts = deptMapper.getAllDept();
            Authority authorityDept0 = new Authority();
            authorityDept0.setPermissionType("dept");
            authorityDept0.setEntityId(entityId);
            List<Authority> authoritiesDept = authorityMapper.getNewAuthority(authorityDept0);//所有部门权限
            Authority authorityStaff0 = new Authority();
            authorityStaff0.setEntityId(entityId);
            authorityStaff0.setPermissionType("staff");
            Map<String, Authority> authoritiesStaffMap = new HashMap<>();
            List<Authority> authoritiesStaff = authorityMapper.getNewAuthority(authorityStaff0);//所有单人权限
            for(Authority authority: authoritiesStaff) authoritiesStaffMap.put(authority.getPermissionId(), authority);
            Map<String, Timestamp> authoritiesDeptIdTime = new HashMap<>();
            Map<String, String> authoritiesDeptIdLevel = new HashMap<>();
            Set<String> hasDept = new HashSet<>();
            for(Authority authorityDept: authoritiesDept){
                hasDept.add(authorityDept.getPermissionId());
                //存储部门的更新时间和权限
                String currentDeptId = authorityDept.getPermissionId();
                authoritiesDeptIdTime.put(currentDeptId, authorityDept.getUpdateTime());
                authoritiesDeptIdLevel.put(currentDeptId, authorityDept.getAuthorityLevel());
                UsUser user = new UsUser();
                user.setDeptId(currentDeptId);
                List<UsUser> users = userMapper.getUser(user);//该部门所有人
                AuthorityInfo authorityInfoDept = new AuthorityInfo();
                authorityInfoDept.setPermissionId(currentDeptId);
                authorityInfoDept.setPermissionName(authorityDept.getPermissionName());
                for(UsUser user1: users){
                    //公司、部门、人
                    AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                    authorityInfoStaff.setPermissionId(user1.getAccount());
                    authorityInfoStaff.setPermissionName(user1.getName() + "_" + user1.getAccount());
                    Timestamp deptUpdateTime = authoritiesDeptIdTime.get(authorityDept.getPermissionId());//部门更新时间
                    Authority authorityStaff = authoritiesStaffMap.get(user1.getAccount());
                    if(authorityStaff != null){//有单人
                        Timestamp staffUpdateTime = authorityStaff.getUpdateTime();//单人更新时间
                        if(authoritiesStaffManagersMap.containsKey(user1.getAccount())) authorityInfoStaff.setAuthorityLevel("4");
                        else if(staffUpdateTime.compareTo(authorityDept.getUpdateTime()) >= 0){//单人比部门新
                            if(staffUpdateTime.compareTo(authorityCompany.getUpdateTime()) >= 0){//单人最新
                                authorityInfoStaff.setAuthorityLevel(authoritiesStaffMap.get(user1.getAccount()).getAuthorityLevel());
                            }
                            else authorityInfoStaff.setAuthorityLevel(authorityCompany.getAuthorityLevel());//公司最新
                        }
                        else{//部门比单人新
                            if(deptUpdateTime.compareTo(authorityCompany.getUpdateTime()) >= 0){//部门最新
                                authorityInfoStaff.setAuthorityLevel(authoritiesDeptIdLevel.get(authorityDept.getPermissionId()));
                            }
                            else authorityInfoStaff.setAuthorityLevel(authorityCompany.getAuthorityLevel());//公司最新
                        }
                    }
                    else{//没有单人
                        if(deptUpdateTime.compareTo(authorityCompany.getUpdateTime()) >= 0){//部门最新
                            authorityInfoStaff.setAuthorityLevel(authoritiesDeptIdLevel.get(authorityDept.getPermissionId()));
                        }
                        else authorityInfoStaff.setAuthorityLevel(authorityCompany.getAuthorityLevel());//公司最新
                    }
                    if(authorityInfoStaff.getAuthorityLevel().equals("4")) authorityInfoDept.addFirstChildren(authorityInfoStaff);
                    else authorityInfoDept.addChildren(authorityInfoStaff);
                }
                if(authorityDept.getAuthorityLevel().equals("4")) authorityInfos.add(0, authorityInfoDept);
                else authorityInfos.add(authorityInfoDept);
            }
            for(UsDept dept: depts){
                String depId = dept.getOrganizationId();
                if(!hasDept.contains(depId)){//这个部门不在表中
                    AuthorityInfo authorityInfoDept = new AuthorityInfo();
                    authorityInfoDept.setPermissionId(depId);
                    authorityInfoDept.setPermissionName(dept.getOrganizationName());
                    UsUser user = new UsUser();
                    user.setDeptId(depId);
                    List<UsUser> users = userMapper.getUser(user);//该部门所有人
                    for(UsUser user1: users){
                        //公司、人
                        AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                        authorityInfoStaff.setPermissionId(user1.getAccount());
                        authorityInfoStaff.setPermissionName(user1.getName() + "_" + user1.getAccount());
                        Authority authorityStaff = authoritiesStaffMap.get(user1.getAccount());
                        if(authorityStaff != null){//有单人
                            Timestamp staffUpdateTime = authorityStaff.getUpdateTime();//单人更新时间
                            if(authoritiesStaffManagersMap.containsKey(user1.getAccount())) authorityInfoStaff.setAuthorityLevel("4");
                            else if(staffUpdateTime.compareTo(authorityCompany.getUpdateTime()) >= 0)//单人比公司新
                                authorityInfoStaff.setAuthorityLevel(authoritiesStaffMap.get(user1.getAccount()).getAuthorityLevel());
                            else authorityInfoStaff.setAuthorityLevel(authorityCompany.getAuthorityLevel());//公司最新
                        }
                        else authorityInfoStaff.setAuthorityLevel(authorityCompany.getAuthorityLevel());//没有单人
                        if(authorityInfoStaff.getAuthorityLevel().equals("4")){
                            if(authorityInfoStaff.getPermissionId().equals(fileManagerAccount)) authorityInfoStaff.setPermissionName("系统文件管理员");
                            authorityInfoDept.addFirstChildren(authorityInfoStaff);
                        }
                        else authorityInfoDept.addChildren(authorityInfoStaff);
                    }
                    authorityInfos.add(authorityInfoDept);
                }
            }
            //单人管理员
            for(String key: authoritiesStaffManagersMap.keySet()){
                AuthorityInfo authorityInfoStaff = new AuthorityInfo();
                authorityInfoStaff.setPermissionId(key);
                if(key.equals(fileManagerAccount)) authorityInfoStaff.setPermissionName("系统文件管理员");
                else authorityInfoStaff.setPermissionName(authoritiesStaffManagersMap.get(key));
                authorityInfoStaff.setAuthorityLevel("4");
                authorityInfos.add(0, authorityInfoStaff);
            }
        }
        return authorityInfos;
    }

    @Override
    public String checkAuthority(String account, String deptId, String entityId) {

        //先判断是否曾经为管理员
        Authority authority = new Authority();
        authority.setEntityId(entityId);
        authority.setAuthorityLevel("4");

        authority.setPermissionId(account);
        authority.setPermissionType("staff");
        if(!getAuthority(authority).isEmpty()) return "4";

        authority.setPermissionId(deptId);
        authority.setPermissionType("dept");
        if(!getAuthority(authority).isEmpty()) return "4";

        authority.setPermissionId(null);
        authority.setPermissionType("0");
        if(!getAuthority(authority).isEmpty()) return "4";

        authority = authorityMapper.checkAuthority(account, deptId, entityId);
        if(authority == null) return "0";
        else return authority.getAuthorityLevel();
    }

    @Override
    @Transactional
    public String initAuthority(String account, String name, String entityId, String level) {
        //子文件夹权限刷新
        String entityName = getEntityNameByEntityId(entityId);
        Authority authority = new Authority();
        authority.setEntityId(entityId);
        authority.setEntityName(entityName);
        authority.setFileOrFolder(entityId.split("_")[0]);
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        authority.setUpdateTime(time);
        authority.setPermissionType("staff");
        authority.setPermissionId(account);
        if(authorityMapper.getAuthority(authority).isEmpty()){
            //没有这个人
            authority.setAuthorityLevel(level);
            authority.setPermissionName(name);
            authority.setCreateTime(time);
            authority.setId(generateId());
            if(!authorityMapper.insertAuthority(authority)){
                log.error("initAuthority: 新增员工权限失败!");
                throw new BusinessException("新增员工权限失败!");
            }
        }
        else{
            authority.setAuthorityLevel(level);
            if(!authorityMapper.updateAuthority(authority)){
                log.error("initAuthority: 更新员工权限失败!");
                throw new BusinessException("更新员工权限失败!");
            }
        }
        return "新增权限成功!";
    }

    @Transactional
    public boolean insertMyselfAndParentAuthority(Authority authority) {
        if(!authorityMapper.insertAuthority(authority)){
            log.error("insertMyselfAndParentAuthority: 新增权限失败!(1)");
            throw new BusinessException("新增权限失败!");
        }
        String entityId = authority.getEntityId();
        if(entityId.startsWith("folder")){
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            folder = folderMapper.getFolder(folder).get(0);
            entityId = folder.getParentId();
        }
        else{
            File file = new File();
            file.setEntityId(entityId);
            file = fileMapper.getFile(file).get(0);
            entityId = file.getParentId();
        }
        authority.setFileOrFolder("folder");
        while(!entityId.equals("root")){//循环从该节点找根，不存在就加入
            Folder currentFolder = new Folder();
            currentFolder.setEntityId(entityId);
            currentFolder = folderMapper.getFolder(currentFolder).get(0);//当前文件夹
            Authority authority0;
            if(authority.getPermissionType().equals("staff")){
                UsUser usUser = new UsUser();
                usUser.setAccount(authority.getPermissionId());
                usUser = userMapper.getUser(usUser).get(0);
                authority0 = authorityMapper.checkAuthority(authority.getPermissionId(), usUser.getDeptId(), entityId);

            }
            else{
                authority0 = authorityMapper.checkDeptAuthority(authority.getPermissionId(), entityId);
            }
            if(authority0 == null){
                authority.setAuthorityLevel("-1");
                authority.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                authority.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                authority.setId(generateId());
                if(!authorityMapper.insertAuthority(authority)){
                    log.error("updateMySelfAndParentAuthority: 新增父文件夹权限失败!");
                    throw new BusinessException("updateMySelfAndParentAuthority: 新增父文件夹权限失败!");
                }
            }
            else if(authority0.getAuthorityLevel().equals("0")){
                authority0.setAuthorityLevel("-1");
                if(!authorityMapper.updateAuthority(authority0)){
                    log.error("updateMySelfAndParentAuthority: 更新父文件夹权限失败!");
                    throw new BusinessException("updateMySelfAndParentAuthority: 更新父文件夹权限失败!");
                }
            }
            entityId = currentFolder.getParentId();
        }
        return true;
    }

    @Transactional
    public boolean updateMySelfAndParentAuthority(Authority authority) {
        int level = Integer.parseInt(authority.getAuthorityLevel());
        if(!authorityMapper.updateAuthority(authority)){
            log.error("updateMySelfAndParentAuthority: 更新权限失败!");
            throw new BusinessException("更新权限失败!");
        }
        if(level > 0){//权限在预览以上，查看父文件夹有没有不可见的
            String entityId = authority.getEntityId();
            if(entityId.startsWith("folder")){
                Folder folder = new Folder();
                folder.setEntityId(entityId);
                folder = folderMapper.getFolder(folder).get(0);
                entityId = folder.getParentId();
            }
            else{
                File file = new File();
                file.setEntityId(entityId);
                file = fileMapper.getFile(file).get(0);
                entityId = file.getParentId();
            }
            authority.setFileOrFolder("folder");
            while(!entityId.equals("root")){//循环从该节点找根，不存在就加入
                Folder currentFolder = new Folder();
                currentFolder.setEntityId(entityId);
                currentFolder = folderMapper.getFolder(currentFolder).get(0);//当前文件夹
                Authority authority0;
                if(authority.getPermissionType().equals("staff")){
                    UsUser usUser = new UsUser();
                    usUser.setAccount(authority.getPermissionId());
                    usUser = userMapper.getUser(usUser).get(0);
                    authority0 = authorityMapper.checkAuthority(authority.getPermissionId(), usUser.getDeptId(), entityId);

                }
                else{
                    authority0 = authorityMapper.checkDeptAuthority(authority.getPermissionId(), entityId);
                }
                if(authority0 == null){
                    authority.setEntityId(entityId);
                    authority.setAuthorityLevel("-1");
                    authority.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                    authority.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                    authority.setId(generateId());
                    if(!authorityMapper.insertAuthority(authority)){
                        log.error("updateMySelfAndParentAuthority: 新增父文件夹权限失败!（2）");
                        throw new BusinessException("updateMySelfAndParentAuthority: 新增父文件夹权限失败!");
                    }
                }
                else if(authority0.getAuthorityLevel().equals("0")){
                    authority0.setAuthorityLevel("-1");
                    if(!authorityMapper.updateAuthority(authority0)){
                        log.error("updateMySelfAndParentAuthority: 更新父文件夹权限失败!（2）");
                        throw new BusinessException("updateMySelfAndParentAuthority: 更新父文件夹权限失败!");
                    }
                }
                entityId = currentFolder.getParentId();
            }
        }
        return true;
    }

    @Override
    @Transactional
    public String updateAuthority(String account, String deptId, String entityId, List<Map<String, String>> depts, List<Map<String, String>> ids, String level) {
        //子文件夹权限刷新
        String authorityStr = checkAuthority(account, deptId, entityId);
        if(!authorityStr.equals("4")) return "您没有管理权限!";
        List<String> entityIds = getChildrenAndMyself(entityId);
        for(String entityId0: entityIds) {
            Authority authority = new Authority();
            authority.setEntityId(entityId0);
            authority.setFileOrFolder(entityId0.split("_")[0]);
            Timestamp time = Timestamp.valueOf(LocalDateTime.now());
            authority.setUpdateTime(time);
            authority.setCreateTime(time);

            //先找部门的4，再找单人的4
            Authority authorityModel = new Authority();
            authorityModel.setAuthorityLevel("4");
            authorityModel.setPermissionType("dept");
            authorityModel.setEntityId(entityId);
            //部门管理员
            List<Authority> authoritiesDept = authorityMapper.getAuthority(authorityModel);

            authorityModel.setPermissionType("staff");
            //单人管理员
            List<Authority> authoritiesStaff = authorityMapper.getAuthority(authorityModel);
            List<String> staffStr = new ArrayList<>();
            for(Authority authority1: authoritiesStaff) staffStr.add(authority1.getPermissionId());

            for(Map<String, String> map: depts){
                authority.setPermissionId(null);
                authority.setPermissionName(null);
                authority.setId(null);
                authority.setAuthorityLevel(null);
                if(map.get("id").equals("000000")){//改公司权限
                    authority.setPermissionType("company");
                    List<Authority> authorities = authorityMapper.getAuthority(authority);
                    authority = authorities.get(0);
                    if(authority.getAuthorityLevel().equals("4")) throw new BusinessException("您无法修改文件管理员" + map.get("label") + "的权限!");

                    authority.setAuthorityLevel(level);
                    if(!updateMySelfAndParentAuthority(authority)){
                        log.error("updateMySelfAndParentAuthority: 更新公司权限失败!(1)");
                        throw new BusinessException("更新公司权限失败!");
                    }

                    //部门管理权限覆盖4
                    authority.setAuthorityLevel("4");
                    authority.setPermissionType("dept");
                    for(Authority authority1: authoritiesDept){
                        authority.setPermissionId(authority1.getPermissionId());
                        authority.setPermissionName(authority1.getPermissionName());
                        if(!authorityMapper.updateAuthority(authority)) {
                            log.error("updateAuthority: 更新部门权限失败!(1)");
                            throw new BusinessException("更新部门权限失败!");
                        }
                    }
                    //单人管理权限覆盖4
                    authority.setAuthorityLevel("4");
                    authority.setPermissionType("staff");
                    for(Authority authority1: authoritiesStaff){
                        authority.setPermissionId(authority1.getPermissionId());
                        authority.setPermissionName(authority1.getPermissionName());
                        if(!authorityMapper.updateAuthority(authority)){
                            log.error("updateAuthority: 更新员工权限失败!(1)");
                            throw new BusinessException("更新员工权限失败!");
                        }
                    }
                }
                else{//改部门权限
                    authority.setPermissionType("dept");
                    authority.setPermissionId(map.get("id"));
                    List<Authority> authorities = authorityMapper.getAuthority(authority);
                    if(authorities.isEmpty()){
                        //这个文件的权限没有这个部门
                        authority.setAuthorityLevel(level);
                        authority.setPermissionName(map.get("label"));
                        authority.setId(generateId());
                        if(!authorityMapper.insertAuthority(authority)){
                            log.error("updateAuthority: 更新部门权限失败!(2)");
                            throw new BusinessException("更新部门权限失败!");
                        }
                        if(!updateMySelfAndParentAuthority(authority)){
                            log.error("updateAuthority: 更新公司权限失败!(2)");
                            throw new BusinessException("更新公司权限失败!");
                        }
                    }
                    else{//有这个部门
                        if(authorities.get(0).getAuthorityLevel().equals("4")) throw new BusinessException("您无法修改文件管理员" + map.get("label") + "的权限!");
                        authority.setAuthorityLevel(level);
                        if(!updateMySelfAndParentAuthority(authority)){
                            log.error("updateAuthority: 更新公司权限失败!(3)");
                            throw new BusinessException("更新公司权限失败!");
                        }
                        authority.setPermissionType("staff");
                        authority.setAuthorityLevel("4");
                        for(Authority authority1: authoritiesStaff){
                            authority.setPermissionId(authority1.getPermissionId());
                            authority.setPermissionName(authority1.getPermissionName());
                            if(!authorityMapper.updateAuthority(authority)){
                                log.error("updateAuthority: 更新员工权限失败!(2)");
                                throw new BusinessException("更新员工权限失败!");
                            }
                        }
                    }
                }
            }
            authority.setPermissionType("staff");
            for(Map<String, String> map: ids){
                authority.setPermissionName(null);
                authority.setId(null);
                authority.setAuthorityLevel(null);
                authority.setPermissionId(map.get("id"));

                //单人存在权限
                List<Authority> authorityStaff1 = authorityMapper.getAuthority(authority);
                if(authorityStaff1.isEmpty()){
                    //这个文件的权限没有这个人
                    authority.setAuthorityLevel(level);
                    authority.setPermissionName(map.get("label"));
                    authority.setId(generateId());
                    if(!authorityMapper.insertAuthority(authority)){
                        log.error("更新员工权限失败!(2)");
                        throw new BusinessException("更新员工权限失败!");
                    }
                }
                else{//有这个人
                    //所有单人管理员staffStr的id
                    if(staffStr.contains(map.get("id"))) throw new BusinessException("您无法修改文件管理员" + map.get("label") + "的权限!");
                    authority.setAuthorityLevel(level);
                    authority.setPermissionName(map.get("label"));
//                    if(!authorityMapper.updateAuthority(authority)){
//                        log.error("更新员工权限失败!(3)");
//                        throw new BusinessException("更新员工权限失败!");
//                    }
                    if(!updateMySelfAndParentAuthority(authority)){
                        log.error("updateAuthority: 更新公司权限失败!(4)");
                        throw new BusinessException("更新公司权限失败!");
                    }

                }
            }
        }
        return "更新权限成功!";
    }

    @Override
    @Transactional
    public String deleteAuthority(String account, String deptId, String entityId, String id, String type) {
        //子文件夹权限刷新
        String authorityStr = checkAuthority(account, deptId, entityId);
        if(!authorityStr.equals("4")) return "您没有管理权限!";
        List<String> entityIds = getChildrenAndMyself(entityId);
        List<UsUser> users = new ArrayList<>();
        if(type.equals("dept")) {
            UsUser userModel = new UsUser();
            userModel.setDeptId(id);
            users = userMapper.getUser(userModel);//该部门所有人
        }
        Authority authorityModel = new Authority();
        for(String entityId0: entityIds) {
            authorityModel.setPermissionType(type);
            authorityModel.setPermissionId(id);
            authorityModel.setEntityId(entityId0);
            if(!authorityMapper.deleteAuthority(authorityModel)){
                log.error("移除权限失败!(1)");
                throw new BusinessException("移除权限失败!");
            }
            authorityModel.setPermissionType("staff");
            for(UsUser user: users){
                authorityModel.setPermissionId(user.getAccount());
                List<Authority> authorities = authorityMapper.getAuthority(authorityModel);
                if(!authorities.isEmpty()){
                    if(authorities.get(0).getAuthorityLevel().equals("4")) continue;
                    if(!authorityMapper.deleteAuthority(authorityModel)){
                        log.error("移除权限失败!(2)");
                        throw new BusinessException("移除权限失败!");
                    }
                }
            }
        }
        return "移除权限成功!";
    }

    @Override
    public List<String> getChildrenAndMyselfRecycleBin(String entityId) {
        //获取全部子文件夹
        List<String> fileFoldersResult = new ArrayList<>();
        if(entityId.startsWith("folder")){
            PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
            personalRecycleBin.setEntityId(entityId);
            String roomId = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin).get(0).getEntityRoom();
            List<Folder> folders = folderMapper.getAllFolderByRoomId(roomId);
            List<File> files = fileMapper.getAllFileByRoomId(roomId);
            List<FileFolder> fileFolders = new ArrayList<>();
            for(Folder folder1: folders) fileFolders.add(new FileFolder(folder1));
            for(File file: files) fileFolders.add(new FileFolder(file));
            fileFolders = TreeUtils.build(fileFolders, entityId);
            for(FileFolder fileFolder: fileFolders){
                List<FileFolder> fileFolders1 = TreeUtils.root2List(fileFolder);
                for(FileFolder fileFolder0: fileFolders1) fileFoldersResult.add(fileFolder0.getEntityId());
            }
        }
        fileFoldersResult.add(entityId);
        return fileFoldersResult;
    }

    @Override
    public List<String> getChildrenAndMyself(String entityId) {
        //获取全部子文件夹
        List<String> fileFoldersResult = new ArrayList<>();
        if(entityId.startsWith("folder")){
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            String roomId = folderMapper.getFolder(folder).get(0).getEntityRoom();
            List<Folder> folders = folderMapper.getAllFolderByRoomId(roomId);
            List<File> files = fileMapper.getAllFileByRoomId(roomId);
            List<FileFolder> fileFolders = new ArrayList<>();
            for(Folder folder1: folders) fileFolders.add(new FileFolder(folder1));
            for(File file: files) fileFolders.add(new FileFolder(file));
            fileFolders = TreeUtils.build(fileFolders, entityId);
            for(FileFolder fileFolder: fileFolders){
                List<FileFolder> fileFolders1 = TreeUtils.root2List(fileFolder);
                for(FileFolder fileFolder0: fileFolders1) fileFoldersResult.add(fileFolder0.getEntityId());
            }
        }
        fileFoldersResult.add(entityId);
        return fileFoldersResult;
    }

    @Override
    public List<FileFolder> getChildrenAndMyself2(String entityId) {
        //获取全部子文件夹
        List<FileFolder> fileFoldersResult = new ArrayList<>();
        if(entityId.startsWith("folder")){
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            String roomId = folderMapper.getFolder(folder).get(0).getEntityRoom();
            List<Folder> folders = folderMapper.getAllFolderByRoomId(roomId);
            List<File> files = fileMapper.getAllFileByRoomId(roomId);
            List<FileFolder> fileFolders = new ArrayList<>();
            for(Folder folder1: folders) fileFolders.add(new FileFolder(folder1));
            for(File file: files) fileFolders.add(new FileFolder(file));
            fileFolders = TreeUtils.build(fileFolders, entityId);
            for(FileFolder fileFolder: fileFolders){
                List<FileFolder> fileFolders1 = TreeUtils.root2List(fileFolder);
                fileFoldersResult.addAll(fileFolders1);
            }
        }
        Folder folder = new Folder();
        folder.setEntityId(entityId);
        folder = folderMapper.getFolder(folder).get(0);
        fileFoldersResult.add(new FileFolder(folder));
        return fileFoldersResult;
    }

    @Override
    @Transactional
    public String insertMember(String account, String deptId, String entityId, List<Map<String, String>> depts, List<Map<String, String>> ids) {
        StringBuilder result = new StringBuilder();
        String authorityStr = checkAuthority(account, deptId, entityId);
        if(!authorityStr.equals("4")) throw new BusinessException("您没有管理权限!");
        //所有子孙权限都更改
        List<String> entityIds = getChildrenAndMyself(entityId);
        String level = "2";
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        //查部门和人权限为4的
        Authority authorityModel = new Authority();
        authorityModel.setAuthorityLevel("4");
        authorityModel.setPermissionType("dept");
        authorityModel.setEntityId(entityId);
        //部门管理员
        List<Authority> authoritiesDept = authorityMapper.getAuthority(authorityModel);
        for(Authority authority: authoritiesDept){
            authority.setUpdateTime(time);
            authorityMapper.updateAuthority(authority);
        }
        authorityModel.setPermissionType("staff");
        //单人管理员
        List<Authority> authoritiesStaff = authorityMapper.getAuthority(authorityModel);
        for(Authority authority: authoritiesStaff){
            authority.setUpdateTime(time);
            authorityMapper.updateAuthority(authority);
        }

        for(String entityId0: entityIds){
            result.append(entityId0).append(":");
            Authority authority = new Authority();
            authority.setEntityId(entityId0);

            if(entityId0.startsWith("folder")) authority.setFileOrFolder("folder");
            else if(entityId0.startsWith("file")) authority.setFileOrFolder("file");
            else{
                log.error("entityId有误!");
                throw new BusinessException("entityId有误!");
            }
            authority.setPermissionType("company");
            authority.setPermissionId("000000");
            List<Authority> authorities = authorityMapper.getAuthority(authority);
            if(!authorities.isEmpty()) return "全部成员已添加!";
            authority.setCreateTime(time);
            authority.setUpdateTime(time);
            for(Map<String, String> map: depts){
                authority.setPermissionId(map.get("id"));
                authority.setPermissionName(null);
                authority.setAuthorityLevel(null);
                authority.setId(null);
                //公司
                if(map.get("id").equals("000000")){
                    authority.setPermissionName(map.get("label"));
                    authority.setAuthorityLevel(level);
                    authority.setId(generateId());
                    authority.setPermissionType("company");
                    if(!insertMyselfAndParentAuthority(authority)){
                        log.error("新增权限失败!(1)");
                        throw new BusinessException("新增权限失败!");
                    }
                    result.append("全部成员已添加!");
                }
                else{
                    authority.setPermissionType("dept");
                    authorities = authorityMapper.getAuthority(authority);
                    if(!authorities.isEmpty()) {
                        result.append(map.get("label")).append("已存在, ");
                        continue;
                    }
                    authority.setPermissionName(map.get("label"));
                    authority.setAuthorityLevel(level);
                    authority.setId(generateId());
                    if(!insertMyselfAndParentAuthority(authority)){
                        log.error("新增权限失败!(2)");
                        throw new BusinessException("新增权限失败!");
                    }
                }
            }
            for(Map<String, String> map: ids){
                //先看部门中是否存在
                authority.setPermissionName(null);
                authority.setAuthorityLevel(null);
                authority.setId(null);
                UsUser user = new UsUser();
                user.setAccount(map.get("id"));
                List<UsUser> users = userMapper.getUser(user);
                if(users.size() > 1){
                    log.error("account不唯一");
                    throw new BusinessException("account不唯一!");
                }
                else if(users.isEmpty()){
                    log.error("account不存在");
                    throw new BusinessException("account不存在!");
                }
                else user = users.get(0);

                authority.setPermissionType("dept");
                authority.setPermissionId(user.getDeptId());
                authorities = authorityMapper.getAuthority(authority);
                if(!authorities.isEmpty()) {
                    result.append(map.get("label")).append("已存在, ");
                    continue;
                }
                //再员工里面有没有
                authority.setPermissionId(map.get("id"));
                authority.setPermissionType("staff");
                authorities = authorityMapper.getAuthority(authority);
                if(!authorities.isEmpty()){
                    result.append(map.get("label")).append("已存在, ");
                    continue;
                }
                authority.setPermissionName(map.get("label"));
                authority.setAuthorityLevel(level);
                authority.setId(generateId());
                if(!insertMyselfAndParentAuthority(authority)){
                    log.error("新增权限失败");
                    throw new BusinessException("新增权限失败!");
                }
            }
            result.append("\n");
        }
        return result + "\n新增权限成功!";
    }

    @Override
    public boolean addFolderManager(String entityId, String account){
        Authority authority = new Authority();
        authority.setEntityId(entityId);
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        authority.setPermissionId(account);
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userMapper.getUser(user).get(0);
        authority.setPermissionName(user.getName());
        if(entityId.startsWith("file")){
            authority.setId(generateId());
            authority.setEntityName(getEntityNameByEntityId(entityId));
            authority.setFileOrFolder("file");
            if(!authorityMapper.insertAuthority(authority)){
                log.error("addFolderManager: 新增权限失败(1)");
                throw new BusinessException("addFolderManager: 新增权限失败!");
            }
        }
        else{
            authority.setFileOrFolder("folder");
            List<String> entities = getChildrenAndMyself(entityId);
            for(String entityId0: entities){
                authority.setId(generateId());
                authority.setEntityName(getEntityNameByEntityId(entityId0));
                authority.setEntityId(entityId0);
                if(!authorityMapper.insertAuthority(authority)){
                    log.error("addFolderManager: 新增权限失败(2)");
                    throw new BusinessException("addFolderManager: 新增权限失败!");
                }
            }
        }
        return true;
    }

    @Override
    public String generateId(){
        return UUID.randomUUID().toString();
    }

    public String getEntityNameByEntityId(String entityId){
        if(entityId == null || entityId.isEmpty()) return null;
        else{
            if(entityId.startsWith("folder")){
                Folder folder = new Folder();
                folder.setEntityId(entityId);
                List<Folder> folders = folderMapper.getFolder(folder);
                if(folders == null || folders.isEmpty()){
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if(personalRecycleBins != null && personalRecycleBins.size() == 1) return personalRecycleBins.get(0).getEntityName();
                }
                else{
                    folder = folders.get(0);
                    return folder.getEntityName();
                }
            }
            else if(entityId.startsWith("file")){
                File file = new File();
                file.setEntityId(entityId);
                List<File> files = fileMapper.getFile(file);
                if(files == null || files.isEmpty()){
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if(personalRecycleBins != null && personalRecycleBins.size() == 1) return personalRecycleBins.get(0).getEntityName();
                }
                else{
                    file = files.get(0);
                    return file.getEntityName();
                }
            }
            return null;
        }
    }
}
